package com.hivekion.common.security;

import com.alibaba.fastjson.JSONObject;
import com.hivekion.common.entity.ResponseData;
import com.hivekion.common.enums.ResultCodeEnum;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component("jwtAuthenticationEntryPoint")
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
      @Override
      public void commence(
	      HttpServletRequest request,
	      HttpServletResponse response,
	      AuthenticationException authException)
	      throws IOException, ServletException {
	    System.out.println("认证失败！" + authException.getMessage());
	    response.setStatus(401);
	    response.setCharacterEncoding("UTF-8");
	    response.setContentType("application/json; charset=utf-8");
	    ResponseData data = ResponseData.error(ResultCodeEnum.UNAUTHORIZE, "");
	    PrintWriter printWriter = response.getWriter();
	    printWriter.write(JSONObject.toJSONString(data));
	    printWriter.flush();
      }
}
